package com.bawei.day20230109.base;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.Observable;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProviders;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author 11295 刘铠源
 * 2023/1/9 10:07
 * @类名 BaseActivity
 */
public abstract class BaseActivity<vm extends BaseViewModel,DBD extends ViewDataBinding> extends AppCompatActivity implements Observable {
    public vm viewmodel;
    public DBD databinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        databinding = DataBindingUtil.setContentView(this, layoutId());
        databinding.setLifecycleOwner(this);
        init();
        initData();
    }

    protected abstract void initData();

    private void init() {
        if (viewmodel==null){
            Class cla=null;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType){
                cla=(Class)((ParameterizedType)type).getActualTypeArguments()[0];
            }else {
                cla=getClass();
            }
            viewmodel=(vm) ViewModelProviders.of(this).get(cla);
        }
    }

    protected abstract int layoutId();
}
